"""
响应发送示例 - 展示Gua框架的统一响应处理
重构版本：基于Linus设计哲学，消除功能重复和硬编码
"统一胜过特殊"
"""

from gua import GuaApp, respond, create_websocket_manager
from gua.sender import send_error
from gua.websocket_utils import create_chat_websocket

app = GuaApp()
ws_manager = create_websocket_manager()

@app.route("/")
async def home():
    """主页 - Linus式重构：简化HTML"""
    return respond("""
    <h1>Hello World</h1>
    <p>
        <a href='/api/users'>用户API</a> |
        <a href='/api/error'>错误示例</a> |
        <a href='/custom'>自定义响应</a> |
        <a href='/protected'>受保护的数据</a>
    </p>
    """)

@app.route("/api/users")
async def get_users():
    """API端点 - 自动检测JSON内容"""
    return respond({"users": ["Alice", "Bob", "Charlie"], "total": 3})

@app.route("/api/error")
async def trigger_error():
    """错误处理示例"""
    return respond({"error": "这是一个错误示例"}, status=500)

@app.route("/custom")
async def custom_response():
    """自定义响应示例"""
    return respond("Custom response", status=200, headers={"x-custom-header": "value"})

@app.route("/protected")
async def protected_data():
    """受保护的数据示例 - Linus式重构：实际保护逻辑"""
    return respond({"message": "这是受保护的数据", "access": "granted", "protected": True})

# 简单的认证中间件
@app.middleware
def auth_middleware(handler):
    async def wrapper(scope, receive, send):
        if scope["path"].startswith("/protected"):
            headers = dict(scope.get("headers", []))
            auth_header = headers.get(b"authorization", b"").decode()
            
            if not auth_header.startswith("Bearer secret-token"):
                await send_error(send, "需要认证", 401)
                return
        
        return await handler(scope, receive, send)
    return wrapper

@app.websocket("/ws")
async def websocket_handler(scope, receive, send):
    """WebSocket处理示例 - Linus式重构：使用通用WebSocket处理器"""
    return await create_chat_websocket(scope, receive, send)

if __name__ == "__main__":
    import subprocess
    import sys
    
    # 使用gua命令显示示例启动信息
    result = subprocess.run([sys.executable, "-m", "gua.cli", "examples.sender_demo:app", "--example-info"],
                          capture_output=True, text=True)
    if result.returncode == 0:
        print(result.stdout)
    else:
        print("错误: 无法显示启动信息")
        print("请手动运行: gua examples.sender_demo:app --example-info")